﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Smallerp.Contracts.DataContracts;
using SmallERP.PinBan.PB.Presenter;
using Smallerp.Contracts;
using SmallERP.Bll.PinBan;
using System.Threading;
using SmallERP.COM;
using DevExpress.XtraEditors.Controls;

namespace SmallERP.PinBan
{
    public partial class FrmAutoPinBanSetting : Form
    {
        public FrmAutoPinBanSetting()
        {
            InitializeComponent();
        }
        public List<OrderInfo_PBDCT> CurrOrderList = new List<OrderInfo_PBDCT>();//要操作的文件报数
        public IOperateDB _OperateDb { get; set; }
        OrderBLL _bll;
        public delegate void PrintPhotosListToSc(List<PhotoInfo_PBDCT> list);

        public event PrintPhotosListToSc Print;


        decimal UseTime, AverageTime, AverageUserful;
        int BoardCount = 0;
        List<DisPalyBoardInfo> CurrBoardList = new List<DisPalyBoardInfo>();
        bool _IsRunning = false;
        bool Isstop = false;
        decimal wasteDis = 0.9m;
        decimal waste = (decimal)PBDataTransfer.Waste;
        int tryTime = 0;//查找照片级别

        int AutoModel = 0;


        private void FrmAutoPinBanSetting_Load(object sender, EventArgs e)
        {
            _bll = new OrderBLL(DataTransfer.Addr, DataTransfer.Port, _OperateDb);
            marqueeProgressBarControl1.Enabled = false;
            textEditFolderNum.Text = CurrOrderList.Count().ToString();
            textEditAllPicNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count()).ToString();
            textEditLeftNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count(ph => ph.IsInBoard == false)).ToString();
            textEditCompleteBoard.Text = "0";
            textEditTimeAll.Text = "0";
            textEditTineAverage.Text = "0";
            string BarText = "";
            if (DataTransfer.curTemplateInfo.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.NoBarCode)
            {
                BarText = " 注释：无";
            }
            else
            {
                BarText = " 注释：自动";
            }
            this.Text += "  打印机：" + DataTransfer.CurPrinerInfo.PName.Trim();// +" 纸型：" + DataTransfer.curTemplateInfo.PaperTypeName + " 纸面：" + DataTransfer.curTemplateInfo.PaperFaceName + " 尺寸：" + DataTransfer.curTemplateInfo.Height + "x" + DataTransfer.curTemplateInfo.Length + BarText;
            IniFile.FilePath = Application.StartupPath;
            backgroundWorkerAll.WorkerReportsProgress = true;
            backgroundWorkerAll.WorkerSupportsCancellation = true;
            backgroundWorkerFolder.WorkerReportsProgress = true;
            backgroundWorkerFolder.WorkerSupportsCancellation = true;
            string isForcePrintstr = IniFile.IniReadValue("PB", "isForcePrint");
            if (string.IsNullOrEmpty(isForcePrintstr))
            {
                IniFile.IniWriteValue("PB", "isForcePrint", "False");
            }
            checkBoxClearFolder.Checked = PBDataTransfer.isForcePrint = Convert.ToBoolean(IniFile.IniReadValue("PB", "isForcePrint"));
            string AutaMakeBigPicStr = IniFile.IniReadValue("PB", "AutaMakeBigPic");
            if (string.IsNullOrEmpty(AutaMakeBigPicStr))
            {
                IniFile.IniWriteValue("PB", "AutaMakeBigPic", "False");
            }
            checkBoxAutaMake.Checked = PBDataTransfer.AutaMakeBigPic = Convert.ToBoolean(IniFile.IniReadValue("PB", "AutaMakeBigPic"));

            string MinLengthPrs=IniFile.IniReadValue("PB", "MinLengthPrs");
            if (string.IsNullOrEmpty(MinLengthPrs))
            {
                IniFile.IniWriteValue("PB", "MinLengthPrs", "30");
            }
            textEditMinLength.Text = PBDataTransfer.MinLengthPrs = IniFile.IniReadValue("PB", "MinLengthPrs");

            string Waste = IniFile.IniReadValue("PB", "Waste");
            if (string.IsNullOrEmpty(Waste))
            {
                IniFile.IniWriteValue("PB", "Waste", "3");
                textEditAllUseful.Text = "3";
            }
            else
            {
                 textEditAllUseful.Text = Waste;

                 PBDataTransfer.Waste = Convert.ToDecimal(Waste);
            }
           
            if (PBDataTransfer.AutaMakeBigPic)
            {
                //simpleButtonBack.Visible = false;
                //checkBoxAutaMake.Visible = false;
                //simpleButtonSure.Enabled = false;
                //checkBoxAutaMake.Enabled = false;
                //simpleButtonSure.Visible = false;
                //simpleButtonCancelSure.Visible = false;
                //simpleButtonStart.Location = new Point(583, 247);
                //simpleButtonStart.Text = "开始";
                //simpleButtonStop.Location = new Point(666, 247);
                //simpleButtonStop.Text = "停止";
                AutaMakeVisableSetting(false);
            }
            else
            {
                //simpleButtonBack.Visible = true;
                //checkBoxAutaMake.Visible = true;
                //simpleButtonSure.Enabled = true;
                //checkBoxAutaMake.Enabled = true;
                //simpleButtonStart.Location = new Point(414, 247);
                //simpleButtonStart.Text = "开始";
                //simpleButtonStop.Location = new Point(498, 247);
                //simpleButtonStop.Text = "停止";
                //simpleButtonSure.Visible = true;
                //simpleButtonSure.Location = new Point(583, 247);
                //simpleButtonCancelSure.Visible = true;
                //simpleButtonCancelSure.Location = new Point(666, 247);
                AutaMakeVisableSetting(true);
            }
            BangdingUnSueBoard();
            if (CurrOrderList.Count == 0)
            {
                simpleButtonSure.Enabled = false;
                simpleButtonStart.Enabled = false;

            }
            if (CurrBoardList.Count == 0)
            {
                simpleButtonBack.Enabled = false;
            }
            waste = Convert.ToDecimal(textEditAllUseful.Text);
            List<BoardTemplate_DCT> bList = DataTransfer.BoardTempalteList.Where(p => p.PaperTypeId == DataTransfer.curTemplateInfo.PaperTypeId && p.PaperFaceId == DataTransfer.curTemplateInfo.PaperFaceId).ToList();
            bList.ForEach(p => p.BoardNameRemark = PBDataTransfer.BoardNameRemark);
            cmkTemplistSelects.Properties.DataSource = bList;
            cmkTemplistSelects.Properties.DisplayMember = "TemplateName";
            cmkTemplistSelects.Properties.ValueMember = "TemplateId";
            string currBoardTempKey = DataTransfer.CurPrinerInfo.PrinterID + DataTransfer.curTemplateInfo.PaperTypeName + DataTransfer.curTemplateInfo.PaperFaceName;
            string selectTempIDS = IniFile.IniReadValue("PB", currBoardTempKey);
            if (string.IsNullOrEmpty(selectTempIDS))
            {
            }
            else
            {
                foreach (string str in selectTempIDS.Split(','))
                {
                    foreach (CheckedListBoxItem item in cmkTemplistSelects.Properties.Items)
                    {
                        if (str.Equals(item.Value.ToString()))
                        {
                            item.CheckState = CheckState.Checked;
                        }
                    }
                }
            }
            string strAutoModel = IniFile.IniReadValue("PB", "AutoModel");
            if (string.IsNullOrEmpty(strAutoModel))
            {
                IniFile.IniWriteValue("PB", "AutoModel", "0");
                strAutoModel = "0";
            }
            if (strAutoModel.Equals("0"))
            {
                radioButtonLong.Checked = true;
                radioButtonWaste.Checked = false;
            }
            else
            {
                radioButtonWaste.Checked = true;
                radioButtonLong.Checked = false;
            }
            string stLengthFlag = IniFile.IniReadValue("PB", "LengthFlag");
            if (string.IsNullOrEmpty(stLengthFlag))
            {
                IniFile.IniWriteValue("PB", "LengthFlag", "0");
            }
            else
            {
                if (stLengthFlag.Equals("0"))
                {
 
                }
            }
        }
        void BangdingUnSueBoard()
        {
            CurrBoardList = new List<DisPalyBoardInfo>();
            List<DisPalyBoardInfoDCT> RtnList = _bll.GetUnSureBoardInfo();
            decimal averageWaste = 0;
            decimal CountAverage = 0;
            foreach (DisPalyBoardInfoDCT dct in RtnList)
            {
                DisPalyBoardInfo info = new DisPalyBoardInfo();
                info.BoardID = dct.BoardID;
                info.Length = dct.Length;
                info.PhotoNum = dct.PhotoNum;
                info.FactLength = dct.FactLength;
                info.BoardTemplate = dct.BoardTemplate;
                //info.UserfulNum = 1-((1-Convert.ToDecimal(dct.UserfulNum.ToString("0.00")))*(decimal)0.9);
                info.UserfulNum = Convert.ToDecimal((100 - ((100 - dct.UserfulNum) * (decimal)0.9)).ToString("0.00"));
                info.UseTime = Convert.ToDecimal(dct.UseTime.ToString("0.0"));
                if ((100 - dct.UserfulNum) > Convert.ToDecimal(textEditAllUseful.Text))
                {
                    info.Selected = true;
                }
                else
                {
                    info.Selected = false;
                }
                info.listPhoto = dct.PhotoList;
                CountAverage += info.UserfulNum;
                CurrBoardList.Add(info);
            }
            if (RtnList.Count != 0)
            {
                averageWaste = CountAverage / RtnList.Count;
            }
            else
            {
                averageWaste = 0;
            }
            textEditAverageUsrful.Text = averageWaste.ToString("0.00");
            if (CurrBoardList.Count > 0)
            {
                simpleButtonSure.Enabled = true;
            }
            gridControlBoard.DataSource = CurrBoardList;
            gridControlBoard.RefreshDataSource();
        }
        private void simpleButtonStart_Click(object sender, EventArgs e)
        {
          
            string StrTempLeteIDs = "";
            if (cmkTemplistSelects.Properties.Items.Count > 0)
            {
                foreach (CheckedListBoxItem item in cmkTemplistSelects.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        BoardTemplate_DCT temp = DataTransfer.BoardTempalteList.FirstOrDefault(p => p.TemplateId == (int)item.Value);
                       
                        StrTempLeteIDs += "," + item.Value;
                    }

                }
            }
            else
            {
               
            }
           
            IniFile.IniWriteValue("PB", DataTransfer.CurPrinerInfo.PrinterID + DataTransfer.curTemplateInfo.PaperTypeName + DataTransfer.curTemplateInfo.PaperFaceName, StrTempLeteIDs.TrimStart(','));

          
            if (simpleButtonStart.Text == "开始计算")
            {
                marqueeProgressBarControl1.Enabled = true;
                _IsRunning = true;
                Isstop = false;
                _bll.IsAutoStop = false;
                //if (radioButtonWaste.Checked)//全部一起拼
                //{

                //    if (!backgroundWorkerAll.IsBusy)
                //    {
                //        backgroundWorkerAll.RunWorkerAsync();
                //    }
                //}
                //else
                //{
                //    if (!backgroundWorkerFolder.IsBusy)
                //    {
                //        backgroundWorkerFolder.RunWorkerAsync();
                //    }
                //}
                if (!backgroundWorkerAll.IsBusy)
                {
                    backgroundWorkerAll.RunWorkerAsync();
                }
                simpleButtonStart.Text = "停止计算";
                //simpleButtonBack.Enabled = false;
                //simpleButtonSure.Enabled = false;
                //checkBoxAutaMake.Enabled = false;
                //checkBoxClearFolder.Enabled = false;
                CompEnableSetting(false);
            }
            else
            {
                marqueeProgressBarControl1.Enabled = false;
                _IsRunning = false;
                _bll.IsAutoStop = true;
                if (radioButtonWaste.Checked)//全部一起拼
                {

                    backgroundWorkerAll.CancelAsync();
                    _IsRunning = false;
                    Isstop = true;
                }
                else
                {
                    backgroundWorkerFolder.CancelAsync();
                    _IsRunning = false;
                }
                simpleButtonStart.Text = "开始计算";
                //simpleButtonBack.Enabled = true;
                //simpleButtonSure.Enabled = true;
                //checkBoxAutaMake.Enabled = true;
                //checkBoxClearFolder.Enabled = true;
                CompEnableSetting(true);

            }
        }
        private void CompEnableSetting(bool boolUseable)
        {
            simpleButtonBack.Enabled = boolUseable;
            simpleButtonSure.Enabled = boolUseable;
            checkBoxAutaMake.Enabled = boolUseable;
            checkBoxClearFolder.Enabled = boolUseable;
            simpleButtonRush.Enabled = boolUseable;
        }
        private void AutaMakeVisableSetting(bool boolVisiable)
        {
            simpleButtonBack.Visible = boolVisiable;
            simpleButtonSure.Visible = boolVisiable;

        }
        private void backgroundWorkerAll_DoWork(object sender, DoWorkEventArgs e)
        {
            if (backgroundWorkerAll.CancellationPending)
            {
                e.Cancel = true;
            }

            List<BoardTemplate_DCT> listTemp = new List<BoardTemplate_DCT>();

            foreach (CheckedListBoxItem item in cmkTemplistSelects.Properties.Items)
            {
                if (item.CheckState == CheckState.Checked)
                {
                    listTemp.Add(DataTransfer.BoardTempalteList.FirstOrDefault(p=>p.TemplateId==(int)item.Value));
                   
                }

            }
            BoardTemplate_DCT outBoardTemplete = new BoardTemplate_DCT();
            while (CurrOrderList.Sum(ph => ph.PhotoList.Count()) > 0 && _IsRunning && !Isstop)
            {
                List<PhotoInfo_PBDCT> listResult;
                decimal outWaste = 0;
                int currLength;
                DateTime stTime = DateTime.Now;
                int inlengthPre = Convert.ToInt32(Convert.ToDecimal(SmallERP.PinBan.PBDataTransfer.MinLengthPrs));
                try
                {
                    listResult = _bll.AutoPinSN2(CurrOrderList.Select(o => o.PhotoList.Where(s=>string.IsNullOrEmpty(s.Photo_Base_Info.DXFFilePath)).ToList()).ToList(), listTemp, DataTransfer.CurPrinerInfo, (decimal)waste, out outWaste, out currLength, inlengthPre, checkBoxClearFolder.Checked, AutoModel, out outBoardTemplete);
                    if ((listResult != null && CheckPhoto(listResult)) || outWaste < 0 || outWaste == 1)
                    {
                        listResult.ForEach(p => p.IsInBoard = false);
                    }
                    else
                    {


                        if (listResult != null && listResult.Count > 0)
                        {
                            DisPalyBoardInfo matchBoard = CurrBoardList.Where(p => p.TemplateID == outBoardTemplete.TemplateId && p.FactLength <= outBoardTemplete.Length * DataTransfer.CurPrinerInfo.PDPI - currLength).FirstOrDefault();
                            if (matchBoard != null && (outWaste * 100) <= waste)
                            {
                                listResult.ForEach(p => p.Location = new Point(p.Location.X + matchBoard.FactLength, p.Location.Y));
                                int result = _bll.CombinBoard(listResult, matchBoard.FactLength, matchBoard.FactLength + currLength, matchBoard.BoardID, DataTransfer.CurPrinerInfo, outBoardTemplete);
                                if (result == 0)
                                {
                                    matchBoard.FactLength = matchBoard.FactLength + currLength;
                                    matchBoard.Length = (decimal)Math.Round((double)matchBoard.FactLength / DataTransfer.CurPrinerInfo.PDPI * 2.54, 2);
                                    matchBoard.listPhoto.AddRange(listResult);
                                }
                                backgroundWorkerAll.ReportProgress(1, matchBoard);//1正常返回
                            }
                            else
                            {

                                int Boardid = _bll.CreateBoard2(listResult, outBoardTemplete, DataTransfer.CurPrinerInfo, (float)outWaste, currLength, false, checkBoxAutaMake.Checked);
                                ////////////////////////
                                //List<PhotoInfo_PBDCT> sourcePList = new List<PhotoInfo_PBDCT>();
                                //foreach (var item in CurrOrderList.Select(o => o.PhotoList).ToList())
                                //{
                                //    sourcePList.AddRange(item.Where(p => !p.IsInBoard).ToList());
                                //}
                                //int aaa = sourcePList.Count(p=>p.IsInBoard==false);
                                //backgroundWorkerAll.ReportProgress(9, aaa);//已经找不到合适的版
                                /////////////////////////
                                if (Boardid > 0)
                                {

                                    CurrOrderList.ForEach(o => o.PhotoList.FindAll(delegate(PhotoInfo_PBDCT photo)
                                    {
                                        if (listResult.FirstOrDefault(p => p.PhotoId == photo.PhotoId) != null)
                                        {
                                            return true;
                                        }
                                        else
                                        {
                                            return false;
                                        }
                                    }).ToList().ForEach(pl => pl.IsInBoard = true));
                                    DisPalyBoardInfo board = new DisPalyBoardInfo();
                                    board.BoardID = Boardid;
                                    board.PhotoNum = listResult.Count();
                                    board.UserfulNum = Math.Round((1 - outWaste * wasteDis) * 100, 2);
                                    board.Length = (decimal)Math.Round((double)currLength / DataTransfer.CurPrinerInfo.PDPI * 2.54, 2);
                                    board.UseTime = (decimal)(DateTime.Now - stTime).TotalSeconds;
                                    board.listPhoto = listResult;
                                    board.FactLength = currLength;
                                    //board.TemplateID = DataTransfer.curTemplateInfo.TemplateId;
                                    board.BoardTemplate = outBoardTemplete;
                                    if (outWaste * 100 > Convert.ToDecimal(textEditAllUseful.Text))
                                    {
                                        board.Selected = true;
                                    }
                                    else
                                    {
                                        board.Selected = false;
                                    }
                                    CurrBoardList.Add(board);

                                    backgroundWorkerAll.ReportProgress(1, board);//1正常返回
                                }
                                else
                                {

                                }
                            }
                        }
                        else
                        {
                            if (!_bll.IsAutoStop)
                            {
                                if (tryTime < 2)
                                {
                                    backgroundWorkerAll.ReportProgress(2, "");//已经找不到合适的版
                                }
                                else
                                {
                                    backgroundWorkerAll.ReportProgress(5, "");//已经找不到合适的版
                                }
                            }

                        }
                    }
                    //}
                    Thread.Sleep(2000);

                }
                catch (Exception ex)
                {
                    backgroundWorkerAll.ReportProgress(3, ex);//3错误
                }
            }
        }
        int currIndex = 0;
        private bool CheckPhoto(List<PhotoInfo_PBDCT> inList)
        {
            int iCount = inList.Count;
            for (int i = 0; i < iCount; i++)
            {
                for (int j = i + 1; j < iCount; j++)
                {
                    //i j位置进行判断矩形是否重合
                    // return true;
                    PhotoInfo_PBDCT P1 = inList[i];
                    PhotoInfo_PBDCT P2 = inList[j];

                    //两个矩形框的边的一半
                    decimal halfP1W = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactHeigth / 2 : P1.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP2W = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactHeigth / 2 : P2.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP1H = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactWidth / 2 : P1.Photo_Base_Info.PixFactHeigth / 2;
                    decimal halfP2H = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactWidth / 2 : P2.Photo_Base_Info.PixFactHeigth / 2;

                    //两个矩形框的中心位置
                    decimal c1x = P1.Location.X + halfP1W;
                    decimal c1y = P1.Location.Y + halfP1H;
                    decimal c2x = P2.Location.X + halfP2W;
                    decimal c2y = P2.Location.Y + halfP2H;
                    //横向判断
                    if (Math.Abs(c1x - c2x) >= halfP1W + halfP2W || Math.Abs(c1y - c2y) >= halfP1H + halfP2H)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }


                }
            }
            return false;
        }

        private void backgroundWorkerAll_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 1)
            {
                gridControlBoard.DataSource = CurrBoardList;
                gridControlBoard.RefreshDataSource();
                textEditLeftNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count(ph => ph.IsInBoard == false)).ToString();
                textEditCompleteBoard.Text = CurrBoardList.Count.ToString();
                textEditTimeAll.Text = CurrBoardList.Sum(p => p.UseTime).ToString("0.00");
                textEditTineAverage.Text = (CurrBoardList.Sum(p => p.UseTime) / CurrBoardList.Count).ToString("0.00");
                textEditAverageUsrful.Text = (CurrBoardList.Sum(p => p.UserfulNum) / CurrBoardList.Count).ToString("0.00");



            }
            else if (e.ProgressPercentage == 2)
            {


                if (tryTime < 2)
                {
                    tryTime++;
                }
            }
            else if (e.ProgressPercentage == 4)
            {
                marqueeProgressBarControl1.Enabled = false;
            }
            else
            {

                marqueeProgressBarControl1.Enabled = false;
                _IsRunning = false;
                _bll.IsAutoStop = true;
                if (radioButtonWaste.Checked)//全部一起拼
                {

                    backgroundWorkerAll.CancelAsync();
                    _IsRunning = false;
                    Isstop = true;
                }
                else
                {
                    backgroundWorkerFolder.CancelAsync();
                    _IsRunning = false;
                }
                simpleButtonStart.Text = "开始计算";
                if (checkBoxAutaMake.Checked)
                {
                    simpleButtonStart.Enabled = true;
                    simpleButtonBack.Enabled = false;
                    simpleButtonSure.Enabled = false;
                }
                else
                {
                    simpleButtonStart.Enabled = true;
                    if (CurrBoardList.Count > 0)
                    {
                        simpleButtonBack.Enabled = true;
                        simpleButtonSure.Enabled = true;
                    }
                    else
                    {
                        simpleButtonBack.Enabled = false;
                        simpleButtonSure.Enabled = false;
                    }
                }
                CompEnableSetting(true);
                //MessageBox.Show("请查看生成图片是否启动");
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + (string)e.UserState);
            }
        }

        private void backgroundWorkerAll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            backgroundWorkerAll.CancelAsync();
        }

        private void simpleButtonStop_Click(object sender, EventArgs e)
        {
            marqueeProgressBarControl1.Enabled = false;
            _IsRunning = false;
            _bll.IsAutoStop = true;
            if (radioButtonWaste.Checked)//全部一起拼
            {

                backgroundWorkerAll.CancelAsync();
                _IsRunning = false;
                Isstop = true;
            }
            else
            {
                backgroundWorkerFolder.CancelAsync();
                _IsRunning = false;
            }
        }

        private void simpleButtonClose_Click(object sender, EventArgs e)
        {
            if (radioButtonWaste.Checked)//全部一起拼
            {

                backgroundWorkerAll.CancelAsync();
                _IsRunning = false;
                Isstop = true;
            }
            else
            {
                backgroundWorkerFolder.CancelAsync();
                _IsRunning = false;
            }
            this.Close();
        }

        private void backgroundWorkerFolder_DoWork(object sender, DoWorkEventArgs e)
        {
            if (backgroundWorkerFolder.CancellationPending)
            {
                e.Cancel = true;
            }
            decimal waste = 1 - Convert.ToDecimal(textEditFolderMinUseful.Text) / 100;


            while (CurrOrderList.Sum(ph => ph.PhotoList.Count()) > 0 && _IsRunning)
            {
                List<PhotoInfo_PBDCT> listResult;
                decimal outWaste = 0;
                int currLength;
                DateTime stTime = DateTime.Now;
                foreach (OrderInfo_PBDCT order in CurrOrderList)
                {
                    backgroundWorkerFolder.ReportProgress(4, order.ProductNum);//1正常返回
                    try
                    {
                        listResult = _bll.AutoPinSN2(order.PhotoList.Where(p => p.IsInBoard == false).ToList(), DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (decimal)waste, out outWaste, out currLength, (int)SmallERP.PinBan.PBDataTransfer.SmallType);
                        if (outWaste > waste || outWaste < 0)
                        {
                            listResult.ForEach(p => p.IsInBoard = false);
                            continue;
                        }
                        else
                        {
                            if (listResult != null && listResult.Count > 0)
                            {
                                int Boardid = _bll.CreateBoard2(listResult, DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, (float)outWaste, currLength, false, true);
                                DisPalyBoardInfo board = new DisPalyBoardInfo();
                                board.BoardID = Boardid;
                                board.PhotoNum = listResult.Count();
                                board.UserfulNum = Math.Round((1 - outWaste) * 100, 2);
                                board.Length = (decimal)Math.Round(currLength / DataTransfer.CurPrinerInfo.PDPI * 2.54, 2);
                                board.UseTime = (decimal)(DateTime.Now - stTime).TotalSeconds;
                                if (outWaste * 100 > Convert.ToInt32(textEditAllUseful.Text))
                                {
                                    board.Selected = true;
                                }
                                else
                                {
                                    board.Selected = false;
                                }

                                CurrBoardList.Add(board);
                                backgroundWorkerFolder.ReportProgress(1, board);//1正常返回
                            }
                            else
                            {
                                continue;
                            }
                        }
                        Thread.Sleep(2000);
                    }
                    catch (Exception ex)
                    {
                        backgroundWorkerFolder.ReportProgress(3, ex);//3错误
                    }
                }
                backgroundWorkerFolder.ReportProgress(2, "");//3错误
            }
        }

        private void backgroundWorkerFolder_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 1)
            {
                gridControlBoard.DataSource = CurrBoardList;
                gridControlBoard.RefreshDataSource();
                textEditLeftNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count(ph => ph.IsInBoard == false)).ToString();
                textEditCompleteBoard.Text = CurrBoardList.Count.ToString();
                textEditTimeAll.Text = CurrBoardList.Sum(p => p.UseTime).ToString("0.00");
                textEditTineAverage.Text = (CurrBoardList.Sum(p => p.UseTime) / CurrBoardList.Count).ToString("0.00");
                textEditAverageUsrful.Text = (CurrBoardList.Sum(p => p.UserfulNum) / CurrBoardList.Count).ToString("0.00");



            }
            else if (e.ProgressPercentage == 2)
            {
                marqueeProgressBarControl1.Enabled = false;
                backgroundWorkerFolder.CancelAsync();
            }
            else if (e.ProgressPercentage == 4)
            {
                groupBox2.Text = "运行状态------正在拼文件夹:" + (string)e.UserState;
            }
            else
            {

            }
        }

        private void backgroundWorkerFolder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            backgroundWorkerFolder.CancelAsync();
        }

        private void gridViewBoard_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void checkBoxClearFolder_CheckedChanged(object sender, EventArgs e)
        {
            IniFile.IniWriteValue("PB", "isForcePrint", checkBoxClearFolder.Checked ? "True" : "False");

        }

        private void textEditAllUseful_EditValueChanged(object sender, EventArgs e)
        {
            IniFile.IniWriteValue("PB", "Waste", textEditAllUseful.Text);



        }

        private void textEditMinLength_EditValueChanged(object sender, EventArgs e)
        {
            IniFile.IniWriteValue("PB", "MinLengthPrs", textEditMinLength.Text);

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void checkBoxAutaMake_CheckedChanged(object sender, EventArgs e)
        {
            IniFile.IniWriteValue("PB", "isForcePrint", checkBoxAutaMake.Checked ? "True" : "False");


            //if (checkBoxAutaMake.Checked)
            //{
            //    simpleButtonSure.Visible = false;
            //    simpleButtonCancelSure.Visible = false;
            //    simpleButtonStart.Location = new Point(583, 247);
            //    simpleButtonStart.Text = "开始";
            //    simpleButtonStop.Location = new Point(666, 247);
            //    simpleButtonStop.Text = "停止";
            //}
            //else
            //{
            //    simpleButtonStart.Location = new Point(414, 247);
            //    simpleButtonStart.Text = "预览";
            //    simpleButtonStop.Location = new Point(498, 247);
            //    simpleButtonStop.Text = "停止";
            //    simpleButtonSure.Visible = true;
            //    simpleButtonSure.Location = new Point(583, 247);
            //    simpleButtonCancelSure.Visible = true;
            //    simpleButtonCancelSure.Location = new Point(666, 247);
            //}

            if (checkBoxAutaMake.Checked)
            {
                AutaMakeVisableSetting(false);
            }
            else
            {
                AutaMakeVisableSetting(true);
                if (CurrBoardList.Count > 0)
                {
                    simpleButtonSure.Enabled = true;
                }
            }
        }

        private void simpleButtonSure_Click(object sender, EventArgs e)
        {
            ///吧预览状态的版 全部修改成等待生成大图
            if (((List<DisPalyBoardInfo>)gridControlBoard.DataSource).ToList().Count > 0)
            {
                int val = _bll.ChangeMakeSure();
                if (val == -1)
                {
                    MessageBox.Show("保存失败,请确认渲染服务已打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("计算结果保存成功，已加入到渲染列表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
        }

        private void simpleButtonCancelSure_Click(object sender, EventArgs e)
        {
            List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>)gridControlBoard.DataSource);
            List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
            int val = _bll.DeleteBoards(BoardIDList);
            if (val == -1)
            {

            }
            else
            {
                BangdingUnSueBoard();
                MessageBox.Show("退版成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void simpleButtonBack_Click(object sender, EventArgs e)
        {
            marqueeProgressBarControl1.Enabled = false;
            _IsRunning = false;
            _bll.IsAutoStop = true;
            if (radioButtonWaste.Checked)//全部一起拼
            {

                backgroundWorkerAll.CancelAsync();
                _IsRunning = false;
                Isstop = true;
            }
            else
            {
                backgroundWorkerFolder.CancelAsync();
                _IsRunning = false;
            }

            List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>)gridControlBoard.DataSource).Where(p => p.Selected).ToList();
            List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
            if (BoardIDList.Count == 0)
            {
                return;
            }
            int val = _bll.DeleteBoards(BoardIDList);
            if (val == -1)
            {

            }
            else
            {
                //BangdingUnSueBoard();
                //刷新数据
                MessageBox.Show("退版成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            //BoardIDList.ForEach(delegate(int boardid)
            //{
            //    DisPalyBoardInfo dpbi = CurrBoardList.FirstOrDefault(d => d.BoardID == boardid);
            //    CurrBoardList.Remove(dpbi);
            //});
            //foreach (int boardid in BoardIDList)
            //{
            //    DisPalyBoardInfo dpbi = CurrBoardList.FirstOrDefault(d => d.BoardID == boardid);
            //    CurrBoardList.Remove(dpbi);
            //}
            //gridControlBoard.DataSource = CurrBoardList;
            //gridControlBoard.RefreshDataSource();
            //if (CurrBoardList.Count() == 0)
            //{
            //    simpleButtonBack.Enabled = false;
            //}
            BangdingUnSueBoard();
            try
            {
                this.Cursor = Cursors.WaitCursor;
                simpleButtonRush.Enabled = false;
                int result = _bll.GetAllOrderInfoByTemplate(DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, out CurrOrderList);
                textEditFolderNum.Text = CurrOrderList.Count().ToString();
                textEditAllPicNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count()).ToString();
                textEditLeftNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count(ph => ph.IsInBoard == false)).ToString();

            }
            catch
            { }
            finally
            {
                this.Cursor = Cursors.Default;
                simpleButtonRush.Enabled = true;
            }
        }

        private void gridViewBoard_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Clicks == 1)
            {
                if (e.RowHandle >= 0 && e.Column.Name == "gridColumn6")
                {
                    DisPalyBoardInfo dbi = (DisPalyBoardInfo)gridViewBoard.GetRow(e.RowHandle);
                    dbi.Selected = !dbi.Selected;
                    gridViewBoard.RefreshData();
                }
            }
            else
            {
                DisPalyBoardInfo dbi = (DisPalyBoardInfo)gridViewBoard.GetRow(e.RowHandle);
                Print(dbi.listPhoto);
            }

        }

        private void FrmAutoPinBanSetting_FormClosing(object sender, FormClosingEventArgs e)
        {
            //List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>)gridControlBoard.DataSource);
            //List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
            //if (BoardIDList.Count == 0)
            //{
            //    return;
            //}
            //int val = _bll.DeleteBoards(BoardIDList);
        }

        private void linkLabelAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrBoardList.ForEach(p => p.Selected = true);
            gridViewBoard.RefreshData();
        }

        private void linkLabelOther_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            CurrBoardList.ForEach(p => p.Selected = !p.Selected);
            gridViewBoard.RefreshData();
        }

        private void simpleButtonRush_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                simpleButtonRush.Enabled = false;
                int result = _bll.GetAllOrderInfoByTemplate(DataTransfer.curTemplateInfo, DataTransfer.CurPrinerInfo, out CurrOrderList);
                textEditFolderNum.Text = CurrOrderList.Count().ToString();
                textEditAllPicNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count()).ToString();
                textEditLeftNum.Text = CurrOrderList.Sum(p => p.PhotoList.Count(ph => ph.IsInBoard == false)).ToString();
            }
            catch
            { }
            finally
            {
                this.Cursor = Cursors.Default;
                simpleButtonRush.Enabled = true;
            }
        }

        private void radioButtonWaste_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonWaste.Checked)
            {
                AutoModel = 1;
                IniFile.IniWriteValue("PB", "AutoModel", "1");
            }
        }

        private void radioButtonFocuse_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonLong.Checked)
            {
                AutoModel = 0;
                IniFile.IniWriteValue("PB", "AutoModel", "0");
            }
        }

        private void cmkTemplistSelects_EditValueChanged(object sender, EventArgs e)
        {
            label1PinbanInfo.Text="";
            string text = "正在拼版:" + DataTransfer.curTemplateInfo.PaperTypeName + "," + DataTransfer.curTemplateInfo.PaperFaceName;
            if (cmkTemplistSelects.Properties.Items.Count > 0)
            {
                foreach (CheckedListBoxItem item in cmkTemplistSelects.Properties.Items)
                {
                    if (item.CheckState == CheckState.Checked)
                    {
                        BoardTemplate_DCT temp=DataTransfer.BoardTempalteList.FirstOrDefault(p => p.TemplateId == (int)item.Value);
                        text += "," + temp.TemplateName;
                    }
                    
                }
            }
            else
            {
                text += "未选择模板";
            }
            label1PinbanInfo.Text = text;
        }

        private void checkBoxLengthFlag_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxLengthFlag.Checked)
            {
                IniFile.IniWriteValue("PB", "LengthFlag", "1");
            }
            else
            {
                IniFile.IniWriteValue("PB", "LengthFlag", "0");

            }
        }
    }
    public class DisPalyBoardInfo
    {
        public int BoardID { get; set; }
        public int PhotoNum { get; set; }
        public decimal UserfulNum { get; set; }
        public decimal UseTime { get; set; }
        public decimal Length { get; set; }
        public bool Selected { get; set; }
        public List<PhotoInfo_PBDCT> listPhoto { get; set; }
        public int TemplateID { get { return BoardTemplate.TemplateId; } }
        public int FactLength { get; set; }
        public string PaperTypeName { get { return BoardTemplate.PaperTypeName; } }
        public string PaperFaceName { get { return BoardTemplate.PaperFaceName; } }
        public string Width { get { return (BoardTemplate.Length * 2.54).ToString("0.00"); } }
        public string Height { get { return (BoardTemplate.Height * 2.54).ToString("0.00"); } }
        public BoardTemplate_DCT BoardTemplate { get; set; }
    }
}
